﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data.SqlClient;

namespace SQLHelper
{
    /// <summary>
    /// 数据库操作的单例类：SQLHelperSingleton
    /// 这个类被拆成两个文件：SQLHelperSingleton.cs、SQLHelperAdapter.cs和SQLHelperEntity.cs
    /// 第一个主要写该类的一些基本属性及其配置方法，第二个主要写可供外部调用的SQL操作方法，最后一个主要写具体的SQL操作方法
    /// </summary>
    public partial class SQLHelperSingleton
    {
        private SqlConnection conn;
        private SqlCommand cmd;
        static private string connStr;

        static private SQLHelperSingleton singleton;

        private SQLHelperSingleton ()
        {
            
        }

        /// <summary>
        /// 配置数据库
        /// </summary>
        /// <param name="connStr"></param>
        static public void SetupDataBase (string connStr)
        {
            if ( !string.IsNullOrEmpty(connStr) )
            {
                SQLHelperSingleton.connStr = connStr;
                SQLHelperSingleton.ShareSingletion().InitSQLObject();
            }
        }

        /// <summary>
        /// 初始化Connection和Command对象
        /// </summary>
        private void InitSQLObject ()
        {
            this.conn = new SqlConnection(SQLHelperSingleton.connStr);
            this.cmd = this.conn.CreateCommand();
        }

        /// <summary>
        /// 获取SQLHelper的单例对象
        /// </summary>
        /// <returns></returns>
        static public SQLHelperSingleton ShareSingletion ()
        {
            if ( SQLHelperSingleton.singleton == null )
            {
                SQLHelperSingleton.singleton = new SQLHelperSingleton();
            }
            return SQLHelperSingleton.singleton;
        }

        /// <summary>
        /// 打开数据库连接
        /// </summary>
        private void OpenConnection ()
        {
            if ( this.conn.State != System.Data.ConnectionState.Open )
            {
                this.conn.Open();
            }
        }

        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        private void CloseConnection ()
        {
            if ( this.conn.State != System.Data.ConnectionState.Closed )
            {
                this.conn.Close();
            }
        }
    }
}
